<template>
  <div class="container">
    <el-card class="table-container">
      <div style="margin: 0 10px 20px 10px">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="分发内容:" prop="content">
            <el-col :span="22">
              <el-input :rows="5" v-model="searchForm.content" clearable type="text" placeholder="请输入流转描述" />
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-date-picker v-model="itemPicker" type="daterange" align="right" unlink-panels range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleAdd" v-if="ifOperation">新增</el-button>
          </el-form-item>

        </el-form>

      </div>
      <el-table :data="tableData.list" :header-row-class-name="'table-head-th'"
        v-loading="queryLoading" highlight-current-row>
        <el-table-column align="center" key="content" show-overflow-tooltip prop="content" label="分发内容" />
        <el-table-column align="center" key="sendTime" show-overflow-tooltip prop="sendTime" label="发送时间" />
        <el-table-column align="center"  key="fileName" show-overflow-tooltip
          prop="sendName" label="分发人">

        </el-table-column>

        <el-table-column align="center" key="status" show-overflow-tooltip
          prop="" label="是否签名">
          <template slot-scope="scope"  v-if="scope.row.isRoot">
            <el-tag type="success" v-if="scope.row.status == 2">
              <span style="font-size: 16px;">&nbsp&nbsp是&nbsp&nbsp</span>
            </el-tag>
            <el-tag type="danger" v-else>
              <span style="font-size: 16px;">&nbsp&nbsp否&nbsp&nbsp</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" key="isDestroyed" show-overflow-tooltip
          prop="status" label="是否销毁">
          <template slot-scope="scope" v-if="scope.row.isRoot">
            <el-tag type="success" v-if="scope.row.isDestroyed == 2">
              <span style="font-size: 16px;">&nbsp&nbsp是&nbsp&nbsp</span>
            </el-tag>
            <el-tag type="danger" v-else>
              <span style="font-size: 16px;">&nbsp&nbsp否&nbsp&nbsp</span>
            </el-tag>
          </template>
        </el-table-column>
        <!-- 表格操作列 -->
        <el-table-column align="center" label="操作" fixed="right" width="250">
          <template slot-scope="scope">
            <div style="display: flex;flex-wrap: nowrap; justify-content: center;">
              <el-button size="mini" title="流程" type="success" @click="handleDetail(scope.row)">
                流程
              </el-button>
              <el-button size="mini" title="签收" v-if="scope.row.isRoot" :disabled="scope.row.status == 2" type="primary"
                @click="handleSignature(scope.row)">
                签收
              </el-button>
              <el-button size="mini" title="销毁" v-if="scope.row.isRoot" :disabled="(scope.row.status == 1 && scope.row.isDestroyed == 1) || scope.row.isDestroyed ==2" type="danger"
                @click="handleDestruction(scope.row)">
                销毁
              </el-button>
              <el-button size="mini" title="统计" v-if="!scope.row.isRoot" type="primary" @click="handleTongji(scope.row)">
                统计
              </el-button>
              <el-button size="mini" title="删除" v-if="!scope.row.isRoot" type="danger" @click="handleDel(scope.row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页信息 -->
      <div class="pagination-container">
        <el-pagination background layout="total, prev, pager, next, jumper" @current-change="handlePageChange"
          @size-change="handleSizeChange" :current-page="pageNum" :total="tableData.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="title" :visible.sync="showEditDialog" :before-close="handleDialogClose">
      <distribution-edit v-if="showEditDialog" :mode="mode" :ifOperation="ifOperation" ref="editForm"
        :record="currentRecord" @after-edit="handleAfterEdit" />
    </el-dialog>
    <el-dialog title="签名" :visible.sync="showSignatureDialog">
      <distributionSignature v-if="showSignatureDialog" :record="currentRecord" @after-signature="handleAfterhandleSig"
        ref="Signature"></distributionSignature>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import DistributionApi from '../api/distribution'
import distributionEdit from './distributionEdit'
import distributionDetails from './distributionDetails.vue'
import ImportExcel from '@/components/ImportExcel'
import DepartmentApi from '../../department/api/department'

import distributionSignature from './distributionSignature.vue'
export default {
  name: 'DistributionList',
  components: {
    distributionEdit,
    distributionDetails,
    ImportExcel,
    distributionSignature
  },
  data() {
    return {
      /* 搜索请求数据*/
      searchForm: {
        sendTimeStart:undefined,
        sendTimeEnd:undefined
      },
      pageSize: 10,
      pageNum: 1,
      // 表格数据
      tableData: {
        list:[],
        results: [],
        total:0
      },
      mode: 'edit',
      // 是否显示添加/编辑对话框
      showEditDialog: false,
      //流转详情
      showDetailsDialog: false,
      //签名弹窗
      showSignatureDialog: false,
      // 当前处理行
      currentRecord: {},
      queryLoading: false,
      exportLoading: false,
      autoWidth: true,
      bookType: 'xlsx',
      itemPicker: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      ifOperation: true,
      title: "新增",
      roles: []
    }
  },
  mounted() {
    this.roles = this.$store.getters.roles
    this.init()

  },
  methods: {
    // 页面初始化
    init() {
      this.handleQuery()
      this.getOperation()
    },
    handleQuery() {

      if(this.itemPicker && this.itemPicker.length>0){
        this.searchForm.sendTimeStart=this.itemPicker[0]
        this.searchForm.sendTimeEnd=this.itemPicker[1]
      }else{
        this.searchForm.sendTimeStart=undefined
        this.searchForm.sendTimeEnd=undefined
      }
      this.pageNum = 1
        this.query()
    },
    getOperation() {
      DepartmentApi
        .queryByCond({}).then(res => {
          if (res.data.code == 200) {
            let target = res.data.data.list.filter(item => item.departmentName == '数据支撑')
            this.ifOperation = target[0].id == this.$store.getters.deptId
          }
        })
    },
    handleExportExcel() {
      this.exportLoading = true
      let param = {}
      param = Object.assign({}, this.searchForm)
      DistributionApi
        .queryByCond(param, 0, 0).then(rspData => {
          let datalist = []
          datalist = rspData.data.data.list
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = [
              '文件ID',
              '父级下发ID',
              '发送人ID',
              '接收人ID',
              '发送时间',
              '状态(1-未签收 2-已签收 3-已销毁)'
            ]
            const filterVal = [
              'fileId',
              'parentId',
              'senderId',
              'receiverId',
              'sendTime',
              'status'
            ]
            const list = datalist
            const data = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: '导出Excel',
              autoWidth: this.autoWidth,
              bookType: this.bookType
            })
            this.exportLoading = false
          })
        }).catch(error => {
          this.exportLoading = false
          if (error.message !== '') {
            Message.error(error.message)
          }
        })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        return v[j]
      }))
    },
    query() {
      return new Promise((resolve, reject) => {
        this.queryLoading = true
        const param = Object.assign({}, this.searchForm)
        DistributionApi
          .queryByCond(param, this.pageSize, this.pageNum)
          .then(response => {
            const data = response.data
            if (data.code === 200) {
              this.tableData.list = response.data.data.records
              this.tableData.total = response.data.data.total
              resolve()
            } else {
              Message.error(data.message)

            }
            this.queryLoading = false
          })
          // .catch(error => {
          //   if (error.message !== '') {
          //     reject(error)
          //   }
          //   this.queryLoading = false
          //   reject(error)
          // })
      })
    },

    //签名按钮
    handleSignature(row) {
      this.currentRecord = Object.assign({}, row)
      this.showSignatureDialog = true
    },
    //销毁按钮
    handleDestruction(row) {
      this.$confirm('确定销毁吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          DistributionApi.destroyFile({distributionId:row.distributionId,nodeId:row.relationId}).then(res=>{
            if(res.data.code == 200){
              Message.success("销毁成功")
              this.query()
            }else{
              Message.error("销毁失败")
            }
          })
        })


    },
    //根节点分发按钮
    handleAdd() {
      this.mode = 'add'
      this.title = "新增"
      this.currentRecord = {}
      this.showEditDialog = true
    },
    //流程按钮
    handleDetail(row) {
      this.$router.push({
        path: '/uniquePath-distributionDetails',
        query: {
          distributionId: row.distributionId,
          content: row.content,
          relationId: row.relationId
        }
      })
    },
    //普通用户分发按钮
    handleDistribution(row) {
      this.mode = 'distribution'
      this.title = "人员分发"
      this.currentRecord = Object.assign({}, row)
      this.showEditDialog = true
    },
    // 处理翻页事件
    handlePageChange(currentPage) {
      this.pageNum = currentPage
      this.query()
    },
    // 处理页面总条数事件
    handleSizeChange(val) {
      this.pageSize = val;
      this.query()
    },
    // 处理对话框关闭事件
    handleDialogClose(done) {
      this.$refs.editForm.resetFields()
      done()
    },
    handleTongji(row){

      DistributionApi.exportDistribution({distributionId:row.distributionId}).then(res=>{
        var a = document.createElement('a');
        var url = window.URL.createObjectURL(res.data);
        a.href = url;
        a.download = row.content+'统计';
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
      })
    },
    handleDel(row) {
      this.$confirm('确定删除吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const param = Object.assign({}, row)
          DistributionApi
            .delete(param)
            .then(response => {
              const data = response.data
              if (data.code === 200) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                })
                this.handleQuery()
              } else {
                Message.error(data.message)
              }
            })
            .catch(error => {
              //console.log(error)
              if (error.message !== '') {
                //Message.error(error.message)
              }
            })
        }).catch(() => {
        })
    },
    // 处理编辑对话框关闭事件
    handleAfterEdit() {
      this.showEditDialog = false
      this.$refs.editForm.resetFields()
      this.query()
    },
    handleAfterhandleSig() {
      this.showSignatureDialog = false

      this.query()
    },
    handledownload(filename, name) {
      DistributionApi.downloadFile(filename).then(res => {
        var a = document.createElement('a');
        var url = window.URL.createObjectURL(res.data);
        a.href = url;
        a.download = name;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
      })
    },
  }
}
</script>
<style>
.container {
  margin: 10px;
}

.table-container {
  margin-top: 0px;
}

.pagination-container {
  margin-top: 30px;
  text-align: right;
}
</style>
